package ihm.panel.admin;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Set;

import ihm.applet.KrakenApplet;
import ihm.panel.TablePanel;
import ihm.tool.AppletConstant;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import bdd.standalone.bean.Camera;
import bdd.standalone.bean.User;

//import bdd.external.bean.Camera;
//import bdd.internal.bean.User;

/**
 * Panneau pour gérer les droits des utilisateurs.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class UserRightsPanel extends TablePanel implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	
	private KrakenApplet applet;
	//private User user;
	private int userID = 1;

	private DefaultTableModel model;
	private JTable table;
	private static String[] COLUMN_NAMES = {"Site", "Caméra", "Droit"};

	private JPanel bottom_jp;
	private JButton back_jb;
	
	/**
	 * Constructeur.
	 * @param applet
	 */
	public UserRightsPanel(KrakenApplet applet) {
		super();
		this.applet = applet;
		//this.user = applet.getUser();
		setLayout(new BorderLayout());

		// Table part!
		model = new DefaultTableModel(populateModel(), COLUMN_NAMES);
		model.addTableModelListener(this);

		table = new JTable(model) {
			private static final long serialVersionUID = 1L;

			//  Returning the Class of each column will allow different
			//  renderers to be used based on Class
			@Override
			@SuppressWarnings({ "unchecked", "rawtypes" })
			public Class getColumnClass(int column) {
				return getValueAt(0, column).getClass();
			}

			@Override
			//  Les deux premières colonnes ne sont pas modifiables
			public boolean isCellEditable(int row, int column) {
				int modelColumn = convertColumnIndexToModel(column);
				return (modelColumn == 0 || modelColumn == 1) ? false : true;
			}
		};
		table.setPreferredScrollableViewportSize(table.getPreferredSize());
		table.setFillsViewportHeight(true);

		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
		table.setRowSorter(sorter);
		
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);

		// Buttons part!
		bottom_jp = new JPanel();

		back_jb = new JButton("Retour");
		back_jb.addActionListener(this);
		back_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);
		bottom_jp.add(back_jb);

		add(bottom_jp, BorderLayout.SOUTH);
	}
	
	@Override
	public Object[][] populateModel() {
		Session session = applet.getSession();
		User user = (User) session.load(User.class, getUserID());
		
		@SuppressWarnings("unchecked")
		List<Camera> allCameras = session.createCriteria(Camera.class).list();
		Set<Camera> userCameras = user.getCameras();

		Object[][] data = new Object[allCameras.size()][COLUMN_NAMES.length];
		//System.out.println("selected "+user.getUser_mail()+" rights, with "+accessList.size()+" cameras");
		//for(Camera c : accessList)
			//System.out.println("\taccess to "+c.getCam_name());
		for(int i=0; i<allCameras.size(); i++) {
			Camera c = allCameras.get(i);
			data[i][0] = c.getSite().getSiteserv_name();
			data[i][1] = c.getCam_name();
			data[i][2] = false;
			//if(accessList.contains(c))
				//data[i][2] = 1;
			for(Camera listed : userCameras)
				if(listed.getCam_id() == c.getCam_id())
					data[i][2] = true;
			
			//System.out.println("looking at "+c.getCam_name()+" with "+c.getUsers().size()+" users");
			//for(User u : c.getUsers())
				//System.out.println("\tuser "+u.getUser_mail());
			// n'affiche pas les utilisateurs liés à la caméra parce que les changements n'ont pas étés reportés sur la base externe -_-
		}
		session.close();
		
		return data;
	}
	
	@Override
	public void updateTableInfo() {
		setLocked(true);
		model.setDataVector(populateModel(), COLUMN_NAMES);
		setLocked(false);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(back_jb))
			((AdministrationPanel) getParent()).setPanel("Lister");
	}
	
	@Override
	public void tableChanged(TableModelEvent e) {
		if(!isLocked()) {
			int row = e.getFirstRow();
			int column = e.getColumn();
			TableModel model = (TableModel) e.getSource();
			
			String columnName = model.getColumnName(column);
			boolean hasRight = (boolean) model.getValueAt(row, column);

			Session session = applet.getSession();
			//Camera cam = (Camera) model.getValueAt(row, column-1); // le nom de la caméra
			Camera cam = (Camera) session.createCriteria(Camera.class).add(Restrictions.like("cam_name", model.getValueAt(row, column-1))).list().get(0);

			System.out.println(cam+"'s "+columnName+" changed to "+hasRight);
			
			User user = (User) session.load(User.class, getUserID());

			Transaction tx = session.beginTransaction();
			if(hasRight) {
				user.getCameras().add(cam);
				cam.getUsers().add(user);
			}
			else {
				user.getCameras().remove(cam);
				cam.getUsers().remove(user);
			}
			session.save(user);
			session.save(cam);
			
			tx.commit();
			session.close();
			// utiliser les rollbacks?
		}
	}

	public int getUserID() { return userID; }
	public void setUserID(int userID) { this.userID = userID; }
	
	//public User getUser() { return user; }
	//public void setUser(User user) { this.user = user; }
	
}
